package com.incar.chuxing.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.PopupMenu;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.incar.chuxing.R;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.utils.IntentKey;
import com.incar.chuxing.utils.Toast.ToastCompat;
import com.just.library.AgentWeb;
import com.just.library.AgentWebConfig;
import com.just.library.ChromeClientCallbackManager;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class WebViewActivity extends BaseActivity {

    @BindView(R.id.container)
    LinearLayout mLinearLayout;

    protected AgentWeb mAgentWeb;
    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_name)
    TextView titleName;
    @BindView(R.id.title_tv_more)
    TextView titleTvMore;

    private AlertDialog mAlertDialog;
    private PopupMenu mPopupMenu;
    private String title;
    private String url;
    private Context mContext = this;
    private boolean isH5Title;
    private String startUrl;


    @Override
    public int getLayoutId() {
        return R.layout.activity_web;
    }

    @Override
    public void initView() {


        Intent intent = getIntent();
        title = intent.getStringExtra(IntentKey.INTENT_WEBVIEW_TITLE);
        isH5Title = intent.getBooleanExtra(IntentKey.INTENT_WEBVIEW_H5TITLE, false);
        url = intent.getStringExtra(IntentKey.INTENT_WEBVIEW_URL);
        if (!isH5Title) {
            titleName.setText(title);
        }
        titleTvMore.setVisibility(View.VISIBLE);
        titleTvMore.setText("更多");
        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(mLinearLayout, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()//
                .defaultProgressBarColor()
                .setReceivedTitleCallback(mCallback)
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setSecutityType(AgentWeb.SecurityType.strict)
                .createAgentWeb()//
                .ready()
                .go(url);

    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && url.contains("#$index$#")) {  //跳首页
                finish();
            } else if (url != null && url.contains("#$car$#")) {
                Intent intent = new Intent(mContext, MainActivity.class);
                intent.putExtra("chooseCar", true);
                startActivity(intent);
            } else if (url != null && url.contains("#$topUp$#")) {
                startActivity(new Intent(mContext, RechargeActivity.class));
                finish();
            } else if (url != null && url.contains("http://www.webcode.com/")) {
                finish();
            } else if (startUrl != null && startUrl.equals(url)) {
                view.loadUrl(url);
            } else {
                return super.shouldOverrideUrlLoading(view, url);
            }
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            startUrl = url;
            //do you  work
            Log.i("Info", url);
        }
    };
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //do you work
//            Log.i("Info","progress:"+newProgress);
        }
    };


    private ChromeClientCallbackManager.ReceivedTitleCallback mCallback = new ChromeClientCallbackManager.ReceivedTitleCallback() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (isH5Title)
                titleName.setText(title);
        }
    };

    @Override
    public void onBackPressed() {
        if (!mAgentWeb.back())
            finish();
    }


    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        Log.i("Info", "result:" + requestCode + " result:" + resultCode);
        mAgentWeb.uploadFileResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //mAgentWeb.destroy();
        mAgentWeb.getWebLifeCycle().onDestroy();
    }

    @OnClick({R.id.title_tv_more, R.id.title_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.title_tv_more:
                showPoPup(view);
                break;
        }
    }

    /**
     * 显示更多菜单
     *
     * @param view 菜单依附在该View下面
     */
    private void showPoPup(View view) {
        if (mPopupMenu == null) {
            mPopupMenu = new PopupMenu(this, view);
            mPopupMenu.inflate(R.menu.web_toolbar_menu);
            mPopupMenu.setOnMenuItemClickListener(mOnMenuItemClickListener);
        }
        mPopupMenu.show();
    }

    //菜单的事件处理
    private PopupMenu.OnMenuItemClickListener mOnMenuItemClickListener = new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {

            switch (item.getItemId()) {
                case R.id.refresh:
                    toCleanWebCache();
                    if (mAgentWeb != null)
                        mAgentWeb.getLoader().reload();
                    return true;

                case R.id.copy:
                    if (mAgentWeb != null)
                        toCopy(mContext, mAgentWeb.getWebCreator().get().getUrl());
                    return true;
                case R.id.default_browser:
                    if (mAgentWeb != null)
                        openBrowser(mAgentWeb.getWebCreator().get().getUrl());
                    return true;
                case R.id.default_clean:
                    toCleanWebCache();
                    return true;
                default:
                    return false;
            }

        }
    };


    //复制字符串
    private void toCopy(Context context, String text) {

        ClipboardManager mClipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        mClipboardManager.setPrimaryClip(ClipData.newPlainText(null, text));

    }

    /**
     * 打开浏览器
     *
     * @param targetUrl 外部浏览器打开的地址
     */
    private void openBrowser(String targetUrl) {
        if (TextUtils.isEmpty(targetUrl) || targetUrl.startsWith("file://")) {
            ToastCompat.makeText(mContext, targetUrl + " 无法使用浏览器打开。", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri url = Uri.parse(targetUrl);
        intent.setData(url);
        startActivity(intent);


    }

    //清除 WebView 缓存
    private void toCleanWebCache() {

        if (this.mAgentWeb != null) {

            //清理所有跟WebView相关的缓存 ，数据库， 历史记录 等。
            this.mAgentWeb.clearWebCache();
            //Toast.makeText(mContext, "已清理缓存", Toast.LENGTH_SHORT).show();
            //清空所有 AgentWeb 硬盘缓存，包括 WebView 的缓存 , AgentWeb 下载的图片 ，视频 ，apk 等文件。
            AgentWebConfig.clearDiskCache(mContext);
        }

    }


}
